import os
import json
import subprocess
import webbrowser
import re

# uniapp配置文件名
manifest_path = "manifest.json"


# 修改版本号
def addVersion():
    if not os.path.exists(manifest_path):
        print(f"{manifest_path} 文件未找到。")
        exit(1)

    try:
        with open(manifest_path, "r", encoding="utf-8") as f:
            manifest = json.load(f)
    except json.JSONDecodeError as e:
        print(f"解析manifest.json文件时出错: {e}")
        exit(1)

    old_version_code = int(manifest.get("versionCode", 0))  # 将版本号转换为整数
    old_version_name = manifest.get("versionName", "0.0.0")

    print(f"旧版本号: {old_version_code}")
    print(f"旧版本名: {old_version_name}")

    # 增加 versionCode
    new_version_code = old_version_code + 1

    # 增加 versionName
    major, minor, patch = map(int, old_version_name.split("."))
    if patch + 1 > 100:
        new_version_name = f"{major}.{minor + 1}.0"
    else:
        new_version_name = f"{major}.{minor}.{patch + 1}"

    # 更新 manifest
    manifest["versionCode"] = new_version_code
    manifest["versionName"] = new_version_name

    with open(manifest_path, "w", encoding="utf-8") as f:
        json.dump(manifest, f, ensure_ascii=False, indent=4)

    print(f"新版本号: {new_version_code}")
    print(f"新版本名: {new_version_name}")

    return new_version_code, new_version_name


# 修改api地址
def changeApi(projectPath, devapi, prodapi):
    print("修改api")
    # 获取config.js文件
    config_path = os.path.join(projectPath, "config.js")
    if not os.path.exists(config_path):
        print("config.js 文件不存在")
        exit(1)
    # 读取config.js文件
    with open(config_path, "r", encoding="utf-8") as f:
        config_content = f.read()
        # 修改config.js文件
        config_content = config_content.replace(devapi, prodapi)
    # 写入config.js文件
    with open(config_path, "w", encoding="utf-8") as f:
        f.write(config_content)
    print("修改api成功")


# 打包apk
def buildApp(command):
    try:
        # 执行命令并逐行读取输出
        process = subprocess.Popen(
            command,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            shell=True,
            text=True,
        )

        # 实时读取输出并检测 URL
        url_pattern = re.compile(r"https://app\.liuyingyong\.cn/build/download/\S+")
        urls = []
        print("开始打包apk")
        for line in process.stdout:
            print(line, end="")  # 实时打印命令输出
            found_urls = url_pattern.findall(line)
            urls.extend(found_urls)

        # 等待进程完成
        process.wait()

        # 检查进程的退出码
        exit_code = process.returncode
        print(f"命令退出码: {exit_code}")

        if exit_code != 0:
            print("命令执行失败")
            exit(1)

        # 下载每个找到的 URL 内容

        for url in urls:
            print("下载地址:", url)
            webbrowser.open(url)
    except Exception as e:
        print(f"打包apk时出错: {e}")
        exit(1)
